#!/usr/bin/env python3
import asyncio
import websockets
import json
import requests

ESURL="http://127.0.0.1:1234/runningGame"

async def handler(websocket):
    # create periodic task:
    asyncio.create_task(send(websocket))
    while True:
        try:
            message = await websocket.recv()
            print(message)
        # client disconnected
        except websockets.ConnectionClosedOK:
            break

async def send(websocket):
    while True:
        r = requests.get(ESURL)
        data = r.json()
        try:
            await websocket.send(json.dumps(data))
        # client disconnected
        except websockets.ConnectionClosedOK:
            break
        await asyncio.sleep(1)


async def main():
    async with websockets.serve(handler, '0.0.0.0', 8080):
        await asyncio.Future()  # run forever

if __name__ == "__main__":
    asyncio.run(main())
